package com.share.beta.web;

import com.alibaba.fastjson.JSONObject;
import com.share.beta.domain.idpid.IdAndPid;
import com.share.beta.domain.idpid.IdAndPidVo;
import com.share.beta.domain.order.OrderFlow;
import com.share.beta.domain.req.UpLoadVo;
import com.share.common.common.Result;
import com.share.common.utils.AESUtil;
import com.share.common.utils.FileUtil;
import com.share.common.utils.RandomUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class MixController {
    @Value("${fileDir.logs}")
    private String fileLogDir;

    @ApiOperation("生产图片验证码加密值---由前端去生产二维码")
    @RequestMapping("/getEncryptCode")
    public Result ImageCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = RandomUtil.getRandomString(4);
        String encrypt = AESUtil.encrypt(code, AESUtil.IMAGE_CODE_KEY);
        log.info("生成的图片验证码code=" + code + ",sessionid=" + request.getSession().getId() + ",encrypt=" + encrypt);
        return Result.success(encrypt);
    }

    @ApiOperation("生成java图片二维码")
    @RequestMapping("/javaImagecode")
    private String javaImagecode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //图片大小
        final int digCount = 6;/*验证码字符串个数*/
        final int fontSize = 12;/*字体大小*/

        final int width = 10 * digCount;
        final int height = width / 2;
        final int startX = 10 * 1;
        final int startY = height / 2 + fontSize / 2;

        String code = RandomUtil.getRandomNumber(digCount);

        // 创建一张内存中的缓存图片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 通过graphics绘制图像
        Graphics graphics = bufferedImage.getGraphics();

        // 设置背景默认黑色
        graphics.setColor(new Color(0xFF, 0xFF, 0xFF));
        graphics.fillRect(0, 0, width - 1, height - 1);

        // 设置画笔颜色为红色
        graphics.setColor(Color.red);

        // 设置字体及大小
        graphics.setFont(new Font("Arial", Font.BOLD, fontSize));
        graphics.drawString(code, startX, startY);

        // 将内存的图片通过浏览器输出流输出成jpg图片
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        return null;
    }

    /**
     * 工单的流程打印
     *
     * @return
     */
    @ApiOperation("工单的流程打印")
    @RequestMapping("/learnProcess")
    public List<OrderFlow> learnProcess() {
        Integer estatus = 4;
        List<OrderFlow> oplist = new LinkedList<>();
        while (estatus != null) {
            /*0待处理 1进行中 2待评价 3已取消 4已打赏5未打赏，建议修改为：1、已申报；2、已接单；3、已派单；4、已修复；5、已评价*/
            switch (estatus) {
                case 0:
                    oplist.add(0, new OrderFlow(estatus, "待处理", "你的工单等待处理中", new Date()));
                    estatus = null;
                    break;
                case 1:
                    oplist.add(0, new OrderFlow(estatus, "进行中", "你的工单正在处理", new Date()));
                    estatus = 0;
                    break;
                case 2:
                    oplist.add(0, new OrderFlow(estatus, "待评价", "你的故障已修复", new Date()));
                    estatus = 1;
                    break;
                case 3:
                    oplist.add(0, new OrderFlow(estatus, "已取消", "你的工单已取消", new Date()));
                    estatus = 2;
                    break;
                case 4:
                    oplist.add(0, new OrderFlow(estatus, "已完成", "", new Date()));
                    estatus = 3;
                    break;
                default:
                    estatus = null;
                    break;
            }
        }
        return oplist;
    }


    @ApiOperation("id与pid目录树构建")
    @RequestMapping("/treeMenu")
    public List<IdAndPidVo> treeMenu(int userId) {
        List<IdAndPid> list = new LinkedList<>();//通过用户id查询出来的用户目录列表

        List<Long> pidInNullList = new LinkedList<>();
        Map<Long, IdAndPidVo> menuMap = new HashMap<>();
        for (IdAndPid menu : list) {// 根据权限创建菜单
            IdAndPidVo menuVo = new IdAndPidVo();
            BeanUtils.copyProperties(menu, menuVo);
            menuMap.put(menu.getPid(), menuVo);
            if (menu.getPid() == null) {
                pidInNullList.add(menu.getPid());
            }
        }

        /*组装树*/
        for (IdAndPid m1 : list) {
            IdAndPidVo menu1 = menuMap.get(m1.getId());
            for (IdAndPid m2 : list) {
                if (m1.getId() != null && m2.getPid() != null && m1.getId().toString().equals(m2.getPid().toString())) {
                    IdAndPidVo menu2 = menuMap.get(m2.getId());
                    List<IdAndPidVo> tmpChildrenList = menu1.getChildren();
                    if (tmpChildrenList == null) {
                        tmpChildrenList = new LinkedList<>();
                        menu1.setChildren(tmpChildrenList);
                    }
                    tmpChildrenList.add(menu2);
                }
            }
        }


        /*提取出所有的树*/
        List<IdAndPidVo> reList = new LinkedList<>();
        for (Long id : pidInNullList) {
            IdAndPidVo menuVo = menuMap.get(id);
            reList.add(menuVo);
        }
        return reList;
    }


    @ApiOperation("多文件上传与接口---postman请求类型是form-data格式")
    @RequestMapping("/upload")
    public Object upload(UpLoadVo load) {
        JSONObject reObj = new JSONObject();
        log.info("收到的参数name={}", load.getName());
        reObj.put("name", load.getName());

        try {
            MultipartFile file1 = load.getFile1();
            if (file1 != null) {
                byte[] bytes = FileUtil.readByte(file1.getInputStream());
                reObj.put("file1name", file1.getOriginalFilename());
                reObj.put("file1length", bytes.length);
            }

            MultipartFile file2 = load.getFile2();
            if (file2 != null) {
                byte[] bytes = FileUtil.readByte(file2.getInputStream());
                reObj.put("file2name", file2.getOriginalFilename());
                reObj.put("file2length", bytes.length);
            }
        } catch (Exception e) {
            log.error("文件读取异常", e);
        }
        log.info("响应信息={}", reObj.toString());
        return reObj;
    }

    @ApiOperation("查询日志文件列表")
    @RequestMapping("/listLog")
    public Result listLog() throws Exception {
        try {
            List<File> list = FileUtil.listCurrentDirFile(fileLogDir, "service", ".log");
            List<String> collect = list.stream().map(File::getAbsolutePath).collect(Collectors.toList());
            return Result.success(collect);
        } catch (Exception e) {
            log.error("获取文件列表异常fileLogDir={}", fileLogDir, e);
            return Result.failure(e.getMessage());
        }
    }

}
